package com.efounder.frame.utils;

import com.efounder.constant.EnvironmentVariable;
import com.efounder.utils.FileUtils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

/**
 * Created by XinQing on 2016/11/3.
 */

public class EFAppAccountFormUtils {

    /***
     * 保存主数据
     * @param jsons
     * 用“;”分割的json
     */
    public static void saveMainData(String jsons, int appAccountID) {
        try {
            String[] jsonStrArray = jsons.split(";");
            for (int i = 0; i < jsonStrArray.length; i++) {
                String firstKey = null;

                String jsonStr = jsonStrArray[i];
                JSONObject jsonObject = JSONObject.fromObject(jsonStr);
                Iterator<String> iterator = jsonObject.keys();
                while (iterator.hasNext()) {
                    String key = iterator.next();
                    if (!"_Self_RowSet".equals(key)) {
                        firstKey = key;
                    }
                }
                if (firstKey != null) {
                    // 判断主数据的更新方式，
                    JSONObject updateObject = jsonObject
                            .getJSONObject("_Self_RowSet");

                    String operation = "0";// 默认为全量更新
                    if (updateObject.has("Operation")) {
                        operation = updateObject.getString("Operation");
                    }
                    String productSign = EnvironmentVariable.getProperty("ProductMark","");

                    switch (operation) {
                        case "0":// 全量更新
                            FileUtils.writeTextFile(EFAppAccountUtils.getAppAccountMDMPath(appAccountID)
                                    + "/mdm_"+productSign + firstKey + ".json", jsonStr);
                            break;
                        case "1":// 增加更新
                            addMainData(firstKey, jsonObject, appAccountID);
                            break;
                        case "2":// 删除更新
                            deleteMainData(firstKey, jsonObject, appAccountID);
                            break;
                        case "3":// 变更更新
                            upateLocalMainData(firstKey, jsonObject, appAccountID);
                            break;

                        default:
                            break;
                    }

                }
            }
            System.out.println("主数据======" + jsons);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 增量更新主数据
     *
     * @param firstKey
     * @param jsonObject
     */
    private static void addMainData(String firstKey, JSONObject jsonObject, int appAccountID) {

        JSONArray dataArray;
        try {
            dataArray = jsonObject.getJSONArray(firstKey);
            String productSign = EnvironmentVariable.getProperty("ProductMark","");

            // 消息中的主数据array
            JSONObject localObject = getLocaMainData(firstKey, appAccountID);// 本地存储的主数据

            if (localObject == null) {
                FileUtils.writeTextFile(EFAppAccountUtils.getAppAccountMDMPath(appAccountID)
                                + "/mdm_"+productSign + firstKey + ".json",
                        jsonObject.toString());
                return;
            }

            if (dataArray != null && dataArray.size() > 0) {
                localObject.getJSONArray(firstKey).addAll(dataArray);
                FileUtils.writeTextFile(EFAppAccountUtils.getAppAccountMDMPath(appAccountID)
                                + "/mdm_"+productSign + firstKey + ".json",
                        localObject.toString());
            }
        } catch (Exception e) {

            e.printStackTrace();
        }
    }

    ;

    /**
     * 删除对应的主数据
     *
     * @param firstKey
     * @param jsonObject
     */
    private static void deleteMainData(String firstKey, JSONObject jsonObject, int appAccountID) {
        JSONArray dataArray = null;// 消息中的
        JSONArray locaDataArray = null;// 本地的
        JSONObject updateObject = null;
        List<String> colList = new ArrayList<>();// 字段的数组

        try {
            dataArray = jsonObject.getJSONArray(firstKey);
            updateObject = jsonObject.getJSONObject("_Self_RowSet");
            String[] keys = updateObject.getString("key").split(",");
            colList = Arrays.asList(keys);
            JSONObject localObject = getLocaMainData(firstKey, appAccountID);
            if (localObject == null) {
                System.out.println("本地为空，不删除");
                return;
            }
            locaDataArray = localObject.getJSONArray(firstKey);
            if (locaDataArray == null) {
                return;
            }
            if (locaDataArray.size() == 0) {
                return;
            }

            if (dataArray != null && dataArray.size() > 0) {
                for (int i = 0; i < dataArray.size(); i++) {
                    JSONObject rowDataObject = dataArray.getJSONObject(i)
                            .getJSONObject("_Self_RowSet");
                    for (int j = 0; j < locaDataArray.size(); j++) {
                        JSONObject localRowDataObject = locaDataArray
                                .getJSONObject(j).getJSONObject("_Self_RowSet");

                        for (int k = 0; k < colList.size(); k++) {
                            String key = colList.get(k);
                            if (rowDataObject.has(key)
                                    && localRowDataObject.has(key)
                                    && !rowDataObject.getString(key).equals(
                                    localRowDataObject.getString(key))) {
                                break;
                            }
                            if (k == colList.size() - 1) {
                                locaDataArray.remove(j);
                                j = j - 1;
                            }
                        }

                    }

                }
                String productSign = EnvironmentVariable.getProperty("ProductMark","");

                FileUtils.writeTextFile(EFAppAccountUtils.getAppAccountMDMPath(appAccountID)
                                + "/mdm_"+productSign + firstKey + ".json",
                        localObject.toString());
            }
        } catch (Exception e) {

            e.printStackTrace();
        }
    }

    ;

    /**
     * 更新本地对应的主数据
     *
     * @param firstKey
     * @param jsonObject
     */
    private static void upateLocalMainData(String firstKey,
                                           JSONObject jsonObject, int appAccountID) {
        JSONArray dataArray = null;// 消息中的
        JSONArray locaDataArray = null;// 本地的
        JSONObject updateObject = null;
        List<String> colList = new ArrayList<>();// 字段的数组

        try {
            dataArray = jsonObject.getJSONArray(firstKey);
            updateObject = jsonObject.getJSONObject("_Self_RowSet");
            String[] keys = updateObject.getString("key").split(",");
            colList = Arrays.asList(keys);
            JSONObject localObject = getLocaMainData(firstKey, appAccountID);
            if (localObject == null) {
                System.out.println("本地为空，不进行更新操作");
                return;
            }
            locaDataArray = localObject.getJSONArray(firstKey);
            if (locaDataArray == null) {
                return;
            }
            if (locaDataArray.size() == 0) {
                return;
            }

            if (dataArray != null && dataArray.size() > 0) {
                for (int i = 0; i < dataArray.size(); i++) {
                    JSONObject rowDataObject = dataArray.getJSONObject(i)
                            .getJSONObject("_Self_RowSet");
                    for (int j = 0; j < locaDataArray.size(); j++) {
                        JSONObject localRowDataObject = locaDataArray
                                .getJSONObject(j).getJSONObject("_Self_RowSet");

                        for (int k = 0; k < colList.size(); k++) {
                            String key = colList.get(k);
                            if (rowDataObject.has(key)
                                    && localRowDataObject.has(key)
                                    && !rowDataObject.getString(key).equals(
                                    localRowDataObject.getString(key))) {
                                break;
                            }
                            if (k == colList.size() - 1) {
                                // 这里进行更新操作
                                // 不要remove在put，put方法会直接把相应位置给替换
//                                locaDataArray
//                                        .put(j, dataArray.getJSONObject(i));
                                locaDataArray.remove(j);
                                locaDataArray.add(j, dataArray.getJSONObject(i));
                            }
                        }

                    }

                }
                String productSign = EnvironmentVariable.getProperty("ProductMark","");

                FileUtils.writeTextFile(EFAppAccountUtils.getAppAccountMDMPath(appAccountID)
                                + "/mdm_"+productSign + firstKey + ".json",
                        localObject.toString());
            }
        } catch (Exception e) {

            e.printStackTrace();
        }
    }


    /**
     * 读取已经存在的主数据
     *
     * @param firstKey
     * @return
     */
    private static JSONObject getLocaMainData(String firstKey, int appAccountID) {

        JSONObject jsonObject = null;
        try {
            // 取出文件的旧的json
            String productSign = EnvironmentVariable.getProperty("ProductMark","");
            String jsonString = FileUtils
                    .readTextFile(EFAppAccountUtils.getAppAccountMDMPath(appAccountID)
                            + "/mdm_"+productSign  + firstKey + ".json");
            jsonObject = JSONObject.fromObject(jsonString);
            String _Self_RowSet = jsonObject.optString("_Self_RowSet");
            if(!_Self_RowSet.equals("")){
                try{
                    JSONObject _Self_RowSetJson = jsonObject.getJSONObject("_Self_RowSet");
                    jsonObject.remove("_Self_RowSet");
                }catch (Exception e){

                }
            }

        } catch (Exception e) {

            e.printStackTrace();
        } finally {
            return jsonObject;
        }

    }

    ;

}
